﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

//using MillsClientGameForm; 
using MillsClient;

namespace ClientMainWindow
{
    public partial class FormStart : Form
    {
        AsynchronoiusIOClient _millsClientObj = null;
        List<string> _machineAdresses = new List<string>();

        public FormStart()
        {
            InitializeComponent();
            cbClientIp.DataSource = GetIPList();
        }

        private List<string> GetIPList()
        {
            List<string> stringIPList = new List<string>();

            System.Net.IPHostEntry localMachineInfo = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
            foreach(System.Net.IPAddress ip in localMachineInfo.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    stringIPList.Add(ip.ToString());
                }
            }
            return stringIPList;            
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (cbClientIp.Text == string.Empty || tbServerPort.Text == string.Empty || tbServerIp.Text == string.Empty)
            {
                MessageBox.Show("Введите все параметры");
            }
            else
            {
                string serverIp = tbServerIp.Text;
                string clientIp = cbClientIp.Text;
                int serverPort = int.Parse(tbServerPort.Text);

                try
                {
                    _millsClientObj = new AsynchronoiusIOClient(serverPort, clientIp, serverIp);
                    _millsClientObj.Start();

                    Logger.WriteLog(string.Format("Connected to: {0}", _millsClientObj.ConnectionInformation.ConnSocket.RemoteEndPoint));

                    btnConnect.Enabled = false;
                    this.Visible = false;
                    MillsAuthForm maf = new MillsAuthForm(ref _millsClientObj);
                    maf.Show();
                    this.Dispose(false);
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(ex.ToString());
                    btnConnect.BackColor = Color.Red;
                    btnConnect.Text = "Подключиться не удалось\nповторите попытку";
                }
            }
        }

        private void FormStart_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_millsClientObj != null)
            {
                _millsClientObj.CloseConnection();
            }
        }
    }
}
